use sea_orm::{ConnectOptions, Database, DatabaseConnection};

use super::app::AppConfig;

pub struct DBPool;

impl DBPool {
    pub async fn init(config: &AppConfig) -> DatabaseConnection {
        let database_url = format!(
            "postgres://{}:{}@{}:{}/{}",
            config.database_user,
            config.database_password,
            config.database_host,
            config.database_port,
            config.database_name,
        );

        log::info!("Database URL: {}", database_url);

        let mut opt = ConnectOptions::new(database_url);
        opt.max_connections(100)
            .min_connections(5)
            .connect_timeout(std::time::Duration::from_secs(30))
            .idle_timeout(std::time::Duration::from_secs(30))
            .test_before_acquire(true)
            .sqlx_logging(config.log_level == "DEBUG");

        let db: DatabaseConnection = Database::connect(opt)
            .await
            .expect("Failed to connect to database");

        db
    }
}
